<route lang="json5">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '聊天室',
  },
}
</route>

<template>
  <view class="chat-wrap">
    <view style="position: relative;flex: 1;">
      <Chat 
        ref="chatRefs"
        :fromUserData="fromUserData"
        :toUserData="toUserData"
        :handleSendMessage="handleSendMessage"
        :getLocalImChatList="getLocalImChatList"
      />
    </view>
  </view>
</template>
  
<script lang="ts" setup>
import WKSDK, { Channel, ChannelTypePerson, Message, MessageText } from "wukongimjssdk"
import Chat from "@/components/chat/index.vue";
import WS from '@/components/chat/ws/index';
import { GetLocalImChatHistory, LoginLocalIm, SendMessage, UserInfoQueryUser } from "@/service/db_user";
import { User } from "@/service/types/user";
import { useCommonStore, useThemeStore, useUserStore } from "@/store";
import { back } from '@/utils';
import { useMessage, useToast } from "wot-design-uni";

// 主题颜色
const { themeConfig } = useThemeStore();
const common = useCommonStore();
const user = useUserStore();
const message = useMessage();
const toast = useToast();

const id = ref('');
const ws = ref(null);
const chatRefs = ref();

/** IM登录 */
const loginLocalIm = async (callback = (token) => {}) => {
  try {
    const res = await LoginLocalIm({
      userId: user.userInfo.id
    })
    const token = res.data || '';
    // const list = token.split(' ');
    // const _token = list[1] || '';
    // callback && callback(_token);
    
    callback && callback(token);
  } catch (error) {
    console.log(error)
  }
}

// 发送信息
const handleSendMessage = async(data, callback) => {

  // try {
  //   // 文本消息
  //   const msgContent = new MessageText(data.message)
  //   // 发送
  //   WKSDK.shared().chatManager.send(msgContent, new Channel(data.toUser, ChannelTypePerson))
  //   callback && callback();
  // } catch (error) {
  //   console.log(error)
  // }
  try {
    const res = await SendMessage(data);
    if (res.code == '6000012') {
      // common.paymentMsgConfirm({
      //   userId: data.fromUser,
      //   type: 'chat',
      //   relatedBusinessId: data.toUser,
      //   relatedBusinessInfo: data.message
      // }, () => {
      //   callback && callback();
      // }, false, message)
      
      // message
      //   .confirm({
      //     msg: `是否直接充值`,
      //     title: '乐缘币不足'
      //   })
      //   .then(() => {
      //     common.confirmPayment({
      //       userId: data.fromUser,
      //       amount: 30
      //     }, () => {
      //       toast.show('充值成功！')
      //     })
      //   })
      //   .catch(() => {
      //     console.log('点击了取消按钮')
      //   })
      return 
    }
    callback && callback();
  } catch (error) {
    console.log(error)
  }
}

// 获取聊天历史记录
const getLocalImChatList = async(data, callback = (res: any) => {}) => {
  try {
    const res = await GetLocalImChatHistory(data);
    callback && callback(res);
  } catch (error) {
    console.log(error)
  }
}

const listen = (message: Message) => {
  console.log('listen message', message)
  if (message.fromUID === user.userInfo.id) return;
  if (message.fromUID !== toUserData.value.id) return;
  chatRefs.value.sendMessage({
    type:'user',
    msg: {
      id: +new Date(),
      time: +new Date(),
      type: 'text',
      content: { text: `${message.content.contentObj}` },
      uid: user.userInfo.id,
    }
  })
}

onLoad((options) => {
  const { conversationID } = options || {};
  id.value = conversationID;
  // 获取接收人的信息
  getUserInfoQueryUser();
})

/** 获取发送人的信息 */
const getFromUserData = () => {
  const _personAvatar: any = user.userInfo.personAvatar || {};
  const _userProfileInfoVo: any = user.userInfo.userProfileInfoVo || {};
  const _matchmakerInfo: any = user.matchmakerInfo || {};
  
  return {
    id: user.userInfo.id,
    avatar: _personAvatar.preUrl || _matchmakerInfo.photoUrl || '',
    nickname: _userProfileInfoVo.nickname || '',
  }
}
const fromUserData = ref({} as any);
fromUserData.value = getFromUserData();

const toUserData = ref<any>({});
/**
 * 获取用户详情
 * @param id 用户id
 */
 const getUserInfoQueryUser = async () => {
  try {
    toUserData.value.id = id.value;
    const res = await UserInfoQueryUser({ id: id.value });
    const data = res.data || {} as User.UserInfoQueryUserDetail;
    const _personAvatar: any = data.personAvatar || {};
    const _userProfileInfoVo: any = data.userProfileInfoVo || {};
    toUserData.value = {
      id: id.value,
      avatar: _personAvatar.preUrl || '',
      nickname: _userProfileInfoVo.nickname || '',
    }
    
    // 设置页面标题
    themeConfig.title = toUserData.value.nickname;

    // IM登录后连接ws
    loginLocalIm((token) => {
      WKSDK.shared().config.addr = 'wss://api.fytxcq.cn/wss/';
      // 认证信息
      WKSDK.shared().config.uid = user.userInfo.id; // 用户uid（需要在悟空通讯端注册过）
      WKSDK.shared().config.token = token; // 用户token （需要在悟空通讯端注册过）
      // 连接
      WKSDK.shared().connectManager.connect();
      WKSDK.shared().chatManager.addMessageListener(listen);
      chatRefs.value.setMyUid(id.value);
      // ws.value = new WS({
      //   data: { token },
      //   onMessage: (res) => {
      //     const data = res.data || {};
      //     if (res.user_id) {
      //       chatRefs.value.setMyUid(res.user_id);
      //       return
      //     }
      //     // 接收消息
      //     if (res.event === 'chat_message') {
      //       chatRefs.value.sendMessage({
      //         type:'user',
      //         msg: {
      //           id: +new Date(),
      //           time: +new Date(),
      //           type: 'text',
      //           content: { text: data.content },
      //           uid: data.from_id, // 0自己 1对方
      //         }
      //       })

      //       console.log('msgList', chatRefs.value.msgList)
      //     }
      //   }
      // });
    })
  } catch (error) {
    console.log('error', error)
  }
}

onUnload(() => {
  // 消息发送状态监听
  WKSDK.shared().chatManager.removeMessageListener(listen);
  // 断开
  WKSDK.shared().connectManager.disconnect();
  themeConfig.isChat = false;
  // ws.value && ws.value.close();
})

onShow(() => {
  nextTick(() => {
    themeConfig.isChat = true;
    // 设置页面标题
    themeConfig.title = '聊天室';
  })
})

onHide(() => {
  // themeConfig.isChat = false;
})
</script>

<style lang="scss" scoped>
.chat-wrap {
  position: absolute;
  width: 100%;
  top: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
}
</style>
